package com.android.functionmanagement.location;

import java.util.ArrayList;

import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.PhoneStateIntentReceiver;
import com.android.internal.telephony.TelephonyProperties;
import android.os.AsyncResult;

import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.ServiceState;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public class CellLocationMode extends LocationMode {

	private Phone phone = null;
	private PhoneStateIntentReceiver mPhoneStateReceiver;
	private static final int EVENT_QUERY_NEIGHBORING_CIDS_DONE = 1000;
	private static final int EVENT_PHONE_STATE_CHANGED = 100;
	private static final int EVENT_SIGNAL_STRENGTH_CHANGED = 200;
	private static final int EVENT_SERVICE_STATE_CHANGED = 300;
	protected static final String TAG = "CellLocationMode";


	@Override
	void init(Context context) {
		this.mContext = context;
		mPhoneStateReceiver = new PhoneStateIntentReceiver(context, mHandler);
        mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
		phone = PhoneFactory.getDefaultPhone();
		if(phone == null)
			return;
		phone.getNeighboringCids(mHandler
		.obtainMessage(EVENT_QUERY_NEIGHBORING_CIDS_DONE));
		CellLocation.requestLocationUpdate();
	}

	@Override
	Object getLocationInfo() {
		return null;
	}

	@Override
	void setLocationCompleteLister(LocationCompleteLister completeLister) {
		this.mCompleteLister = completeLister;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			 AsyncResult ar;
			switch (msg.what) {
			case EVENT_QUERY_NEIGHBORING_CIDS_DONE:
				ar = (AsyncResult) msg.obj;
				String data;
				if (ar.exception == null) {
					data = updateNeighboringCids((ArrayList<NeighboringCellInfo>) ar.result);
				} else {
					data = "unknown";
				}
				Log.d(TAG, "data:" + data);
				if (mCompleteLister != null && data != null
						&& !"unknown".equals(data)) {
					mCompleteLister.onCompleted((ArrayList<NeighboringCellInfo>) ar.result, SUCCESS);
				} else if (mCompleteLister != null) {
					mCompleteLister.onCompleted(null, ERR);
				}
				break;
			case EVENT_SIGNAL_STRENGTH_CHANGED:
                updateSignalStrength();
                break;
			}

		}

	};

	private final String updateNeighboringCids(//相邻基站
			ArrayList<NeighboringCellInfo> cids) {
		StringBuilder sb = new StringBuilder();
		if (cids != null) {
			if (cids.isEmpty()) {
				sb.append("no neighboring cells");
			} else {
				for (NeighboringCellInfo cell : cids) {
					sb.append(cell.toString()).append(" ");
				}
			}
		} else {
			sb.append("unknown");
		}
		return sb.toString();
	}
	//updateLocation(mTelephonyManager.getCellLocation())
	private final void updateLocation(CellLocation location) {//地点
        Resources r = mContext.getResources();
        if (location instanceof GsmCellLocation) {
            GsmCellLocation loc = (GsmCellLocation)location;
            int lac = loc.getLac();
            int cid = loc.getCid();
           /* mLocation.setText(r.getString(R.string.radioInfo_lac) + " = "
                    + ((lac == -1) ? "unknown" : Integer.toHexString(lac))
                    + "   "
                    + r.getString(R.string.radioInfo_cid) + " = "
                    + ((cid == -1) ? "unknown" : Integer.toHexString(cid)));*/
        } else if (location instanceof CdmaCellLocation) {
            CdmaCellLocation loc = (CdmaCellLocation)location;
            int bid = loc.getBaseStationId();
            int sid = loc.getSystemId();
            int nid = loc.getNetworkId();
            int lat = loc.getBaseStationLatitude();
            int lon = loc.getBaseStationLongitude();
           /* mLocation.setText("BID = "
                    + ((bid == -1) ? "unknown" : Integer.toHexString(bid))
                    + "   "
                    + "SID = "
                    + ((sid == -1) ? "unknown" : Integer.toHexString(sid))
                    + "   "
                    + "NID = "
                    + ((nid == -1) ? "unknown" : Integer.toHexString(nid))
                    + "\n"
                    + "LAT = "
                    + ((lat == -1) ? "unknown" : Integer.toHexString(lat))
                    + "   "
                    + "LONG = "
                    + ((lon == -1) ? "unknown" : Integer.toHexString(lon)));*/
        } else {
           // mLocation.setText("unknown");
        }


    }
	//信号强度
	 void updateSignalStrength() {
	        // TODO PhoneStateIntentReceiver is deprecated and PhoneStateListener
	        // should probably used instead.
//	        int state = mPhoneStateReceiver.getServiceState().getState();
//	        Resources r = mContext.getResources();
//
//	        if ((ServiceState.STATE_OUT_OF_SERVICE == state) ||
//	                (ServiceState.STATE_POWER_OFF == state)) {
//	            //dBm.setText("0");
//	        }
//
//	        int signalDbm = mPhoneStateReceiver.getSignalStrengthDbm();
//
//	        if (-1 == signalDbm) signalDbm = 0;
//
//	        int signalAsu = mPhoneStateReceiver.getSignalStrengthLevelAsu();
//
//	        if (-1 == signalAsu) signalAsu = 0;

//	        dBm.setText(String.valueOf(signalDbm) + " "
//	            + r.getString(R.string.radioInfo_display_dbm) + "   "
//	            + String.valueOf(signalAsu) + " "
//	            + r.getString(R.string.radioInfo_display_asu));
	    }
}
